//
//  LoginMyAccount.m
//  Bespoke
//
//  Created by Cheng on 12/8/29.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "LoginMyAccount.h"
#import "AppDelegate.h"
#import "GDataXMLNode.h"
#import "AccountParser.h"
#import <Accounts/Accounts.h>
#import "RequestAPIFunction.h"
#import<Twitter/Twitter.h>
#import "LoadingUI.h"

#define LOADINGVIEW_TAG 10000000
#define LOADINGIMAGE_TAG 20000000

#define SIGNIN_SUCCESS_TAG 101

#define USERINFO_API @"http://54.235.166.43/BeSpokeAPI/userInfo.php"

@implementation LoginMyAccount
@synthesize Array_AccountInfo, BK_En_object, TF_email, TF_password;
@synthesize pSession;
@synthesize delegate;

- (IBAction)SignInPressed:(id)sender {
    
    [TF_email resignFirstResponder];
    [TF_password resignFirstResponder];
    
    if (([TF_email.text isEqualToString:@""])||(TF_email.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter Email." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    else if (([TF_password.text isEqualToString:@""])||(TF_password.text==nil)) {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please enter Password." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
        return;
    }
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:
     ^(void) {
         
         [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
         
         [self RequestAPI:TF_email.text SetPassWord:TF_password.text SetFullName:nil SetSource:@"Bespoke"];
         
         [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];
     }];
}

- (IBAction)SignUpAccountPressed:(id)sender {
    
    [delegate CreateAccountPressed_NonFirst];
}

- (IBAction)ForgotPassword:(id)sender {
    
    [delegate ForgotPassWordPressed_NonFirst];
}

#pragma mark - Facebook

- (IBAction)SignInFacebookPressed:(id)sender {
    
    AppDelegate *BespokeAppDelegate = [[UIApplication sharedApplication] delegate];

    NSArray *permissions = [NSArray arrayWithObjects:
                            @"user_photos",
                            @"user_videos",
                            @"photo_upload",
                            @"publish_stream",
                            @"offline_access",
                            @"user_checkins",
                            @"friends_checkins",
                            @"email",
                            @"user_location",
                            @"read_stream", nil];
    
    pSession = [[FBSession alloc] initWithAppID:@"250527955081918" permissions:permissions urlSchemeSuffix:nil tokenCacheStrategy:nil];

    
    BespokeAppDelegate.session = pSession;

    [BespokeAppDelegate.session openWithCompletionHandler:^(FBSession *session,
                                                            FBSessionState status,
                                                            NSError *error) {
        // and here we make sure to update our UX according to the new session state
        [self updateFBAPI];
    }];
}

-(void)updateFBAPI
{
    [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
    
    AppDelegate *beSpokeAppDelegate = [[UIApplication sharedApplication] delegate];
    
    FBRequest *me = [[FBRequest alloc] initWithSession:beSpokeAppDelegate.session graphPath:@"me"];
    
    [me startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error)
     {
         NSString *result = [NSString stringWithFormat:@"https://graph.facebook.com/%@/home?access_token=%@", user.id, beSpokeAppDelegate.session.accessToken];
         
          if(beSpokeAppDelegate.session.isOpen)
          {
             NSLog(@"Facebook API Link = %@",result ) ;
             
             
             [self RequestAPI:[user objectForKey:@"email"] SetPassWord:@"" SetFullName:[NSString stringWithFormat:@"%@ %@",user.first_name,user.last_name] SetSource:@"Facebook"];
         
             [BK_En_object setAccountInfoFaceBookID:user.id setFaceBookTotken:beSpokeAppDelegate.session.accessToken];
         
         dispatch_async(dispatch_get_main_queue(), ^{
             UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Login has been sucessful." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
             [AlertView setTag:SIGNIN_SUCCESS_TAG];
             [AlertView show];
             });
        }
         else {
             NSLog(@"Facebook Called Failed" ) ;
             [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];
         }
     }];
}


#pragma mark - Twitter

- (IBAction)SignInTwitterPressed:(id)sender {
    
    ACAccountStore *accountStore = [[ACAccountStore alloc] init];
    ACAccountType *twitterType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
    
    [accountStore requestAccessToAccountsWithType:twitterType withCompletionHandler:^(BOOL granted, NSError *error) {
        if (!granted) {
        }
        else {
            NSArray *accounts = [accountStore accountsWithAccountType:twitterType];
            ACAccount *ACA_Array = [accounts objectAtIndex:0];
            if ([ACA_Array valueForKey:@"username"]==nil) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please set up your Twitter account in your Personal settings?" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [AlertView show];
                });
                return;
            }
            
            if ([[ACA_Array valueForKey:@"username"] rangeOfString:@"@"].location == NSNotFound) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Could you please enter your full email in your iPad's Twitter settings - For examlple: @name@email.com - Thank you!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                    [AlertView show];
                });
                return;
            }
            
            [NSThread detachNewThreadSelector:@selector(threadStartAnimating) toTarget:self withObject:nil];
            
            [self RequestAPI:[ACA_Array valueForKey:@"username"] SetPassWord:@"" SetFullName:[[ACA_Array valueForKey:@"properties"] valueForKey:@"fullName"] SetSource:@"Twitter"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Login has been sucessful." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                [AlertView setTag:SIGNIN_SUCCESS_TAG];
                [AlertView show];
            });
            
            [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];
        }
    }];
}

-(void)RequestAPI:(NSString *)UserName SetPassWord:(NSString *)PassWord SetFullName:(NSString *)FullName SetSource:(NSString *)AccountSource {
    
    NSData *responseData = 
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<Authentication UserName=\"%@\" Password=\"%@\" Name=\"%@\" Source =\"%@\" Plaintext=\"True\" />",
                               UserName, PassWord, FullName, AccountSource]
                    urlString:USERINFO_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
    
    self.Array_AccountInfo = [AccountParser loadAccountInfo:responseData];
    
    
    if ([self.Array_AccountInfo count]!=0) {
        
        AccountInfo *AccountInfoOB = (AccountInfo *)[Array_AccountInfo objectAtIndex:0];
        
        [self.BK_En_object setAuthenticationUserName:UserName Password:PassWord];
        [self.BK_En_object setAccountInfoFullName:AccountInfoOB.NS_AccountFullName setPartner:nil];
        [self.BK_En_object setAccountChannel:AccountInfoOB.NS_Channel];
        [self.BK_En_object setAccountYourCalendar:AccountInfoOB.NS_WeddingDate];
        
        [self.BK_En_object setAccountInfoFaceBookID:AccountInfoOB.Feed.Ob_Facebook.NS_FacebookID setFaceBookTotken:AccountInfoOB.Feed.Ob_Facebook.NS_FacebookToken];
        [self.BK_En_object setFacebookONorOff:AccountInfoOB.Feed.Ob_Facebook.FacebookSwitch];
        
        [self.BK_En_object setAccountInfoTwitterKey:AccountInfoOB.Feed.Ob_Twitter.NS_TwitterKey setTwitterSecret:AccountInfoOB.Feed.Ob_Twitter.NS_TwitterSecret];
        [self.BK_En_object setTwitterONorOff:AccountInfoOB.Feed.Ob_Twitter.TwitterSwitch];
        
        [self.BK_En_object setAccountInfoTumblr:AccountInfoOB.Feed.Ob_Tumblr.NS_TumblrName];
        [self.BK_En_object setTumblrONorOff:AccountInfoOB.Feed.Ob_Tumblr.TumblrSwitch];
        
        [self.BK_En_object setAccountInfoInstagram:AccountInfoOB.Feed.Ob_Instagram.NS_InstagramToken];
        [self.BK_En_object setInstagramONorOff:AccountInfoOB.Feed.Ob_Instagram.InstagramSwitch];
        
        for (AccountGoogleFeed *CurrentGoogleFeed in AccountInfoOB.Feed.Array_GoogleFeed) {
            
            int GoogleIndex = [AccountInfoOB.Feed.Array_GoogleFeed indexOfObject:CurrentGoogleFeed];
            
            [self.BK_En_object setAccountInfoGoogleReader:CurrentGoogleFeed.NS_GoogleTitle
                                               SetContent:CurrentGoogleFeed.NS_GoogleContent
                                               SetWebLink:CurrentGoogleFeed.NS_GoogleLink];
            [self.BK_En_object setGoogleSwitchCheck:CurrentGoogleFeed.GoogleFeedSwitch
                                           SetIndex:GoogleIndex];
        }
    }
    
    //Check that user login successful.
    if ([AccountSource isEqualToString:@"Bespoke"]) {
        
        NSError *error;
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:responseData options:0 error:&error];
        
        //Check to upload is success.
        if ([[doc nodesForXPath:@"//Unsuccess" error:&error] count]!=0) {
            
            NSString *Message = [[[[doc nodesForXPath:@"//Unsuccess" error:nil] objectAtIndex:0] attributeForName:@"Message"] stringValue];
            UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:Message delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [AlertView show];
        }
        else {
            
            UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Success" message:@"Login has been sucessful." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
            [AlertView setTag:SIGNIN_SUCCESS_TAG];
            [AlertView show];
        }
    }
}

#pragma mark - UIAlertViewDelegate

- (void)didPresentAlertView:(UIAlertView *)alertView {
    
    [NSThread detachNewThreadSelector:@selector(threadStopAnimating) toTarget:self withObject:nil];
}

- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    if (alertView.tag == SIGNIN_SUCCESS_TAG) {
        [self.delegate SignInSuccess];
    }
}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    if(textField == TF_email)
        [TF_password becomeFirstResponder];
    else if(textField == TF_password)
        [self SignInPressed:textField];
    return YES;
}


#pragma mark - LoadingUI

-(void)threadStartAnimating {
    
    [self addSubview:[LoadingUI LoadingView:self.superview.bounds.size.width SetHeight:self.superview.bounds.size.height]];
    [self addSubview:[LoadingUI LoadingImage:self.superview.bounds.size.width SetHeight:self.superview.bounds.size.height]];
}

-(void)threadStopAnimating {
    
    [[NSOperationQueue mainQueue] addOperationWithBlock:
     ^(void) {
         [[self viewWithTag:LOADINGVIEW_TAG] removeFromSuperview];
         [[self viewWithTag:LOADINGIMAGE_TAG] removeFromSuperview];
     }];
}

@end
